<template>
  <div ref="chart" style="width:100%; height: 400px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import { mapGetters } from 'vuex';
export default {
  name: 'OrderChart',
  computed: {
    ...mapGetters(['sidebar']) // 获取侧边栏状态
  },
  props: {
    chartData: {
      type: Array,
      default: () => [],
    },
  },
  mounted() {
    this.initChart();
  },
  watch: {
    'sidebar.opened': {
      immediate: true, // 立即执行一次
      handler(newVal) {
        console.log(newVal)
        this.$nextTick(() => {
          window.addEventListener('resize', () => this.myChart.resize());
        });
      }
    },
    // 深度监听数据变化
    chartData: {
      deep: true,
      handler(newData) {
        this.initChart(newData);
      }
    }
  },
  data() {
    return {
      myChart: null,
      resizeObserver: null  // 添加ResizeObserver实例
    };
  },
  beforeDestroy() {
    this.cleanup();
  },
  methods: {
    cleanup() {
      // 移除ResizeObserver
      if (this.resizeObserver) {
        this.resizeObserver.disconnect();
      }
      // 移除window.resize监听
      if (this.resizeHandler) {
        window.removeEventListener('resize', this.resizeHandler);
      }
      // 销毁图表实例
      if (this.myChart) {
        this.myChart.dispose();
      }
    },
    initChart() {
      const chartDom = this.$refs.chart;
      this.myChart = echarts.init(chartDom);

      // 提取日期、观影订单数据、兑换订单数据
      const dates = this.chartData.map(item => item.date);
      const viewData = this.chartData.map(item => item.view);
      const exchangeData = this.chartData.map(item => item.exchange);

      const option = {
        // 标题（可选）
        // title: {
        //   text: '订单统计',
        //   left: 'center',
        // },

        // 提示框（鼠标悬停显示详细信息）
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow', // 显示阴影指示器
          },
          formatter: params => {
            const date = params[0].axisValue;
            let html = `<div>${date}</div>`;
            params.forEach(param => {
              if (param.seriesName === '观影订单') {
                html += `<div style="margin: 5px 0;background: rgba(238, 71, 59, .1);display: flex;justify-content: space-between;width:230px;border-radius: 4px;padding: 9px 18px 8px 9px">
                <div>
                <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%;background: linear-gradient(180deg, #EE473B 0%, rgba(255,255,255,0) 100%); margin-right: 5px;"></span>
                <span style="color: #EE473B;font-size: 14px;font-family: DingTalk JinBuTi;font-weight: 400;">${param.seriesName}</span>
                </div>
                <span style="color: #333333;font-size: 14px;font-family: DingTalk JinBuTi;font-weight: 400;">${param.value}</span>
              </div>`;
              } else if (param.seriesName === '兑换订单') {
                html += `<div style="margin: 5px 0;background: rgba(69, 155, 241, .1);display: flex;justify-content: space-between;width:230px;border-radius: 4px;padding: 9px 18px 8px 9px">
                <div>
                <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: linear-gradient(180deg, #4198F0 0%, rgba(255,255,255,0) 100%); margin-right: 5px;"></span>
                <span style="color: #449AF0;font-size: 14px;font-family: DingTalk JinBuTi;font-weight: 400;">${param.seriesName}</span>
                </div>
                <span style="color: #333333;font-size: 14px;font-family: DingTalk JinBuTi;font-weight: 400;">${param.value}</span>
              </div>`;
              }

            });
            return html;
          },
        },

        // 图例（显示“观影订单”和“兑换订单”）
        legend: {
          data: ['观影订单', '兑换订单'],
          top: '5%',
          right: '3%'
        },

        // 网格配置（调整图表边距）
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },

        // X轴（日期）
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            color: '#666',
          },
          axisLine: {
            lineStyle: {
              color: '#ccc',
            },
          },
        },

        // Y轴（金额/数量）
        yAxis: {
          type: 'value',
          name: '金额',
          nameTextStyle: {
            color: '#303030',
            fontSize: '12px',
            padding: [0, 35, 10, 0]
          },
          axisLabel: {
            color: '#666',
          },
          axisLine: {
            lineStyle: {
              color: '#ccc',
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#eee',
            },
          },
        },

        // 堆叠柱状图系列
        series: [
          {
            name: '观影订单',
            type: 'bar',
            stack: 'total', // 堆叠标识
            data: viewData,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: '#EE473B' }, // 顶部颜色
                  { offset: 1, color: '#FFFFFF' }, // 底部颜色
                ],
              },
              // borderRadius: [4, 4, 0, 0], // 圆角（顶部左右）
            },
            barWidth: '20px',
            label: {
              // show: true,
              // position: 'inside', // 标签显示在柱子内部
              // color: '#fff', // 白色字体
              // formatter: '{c}', // 显示数值
            },
          },
          {
            name: '兑换订单',
            type: 'bar',
            stack: 'total', // 堆叠标识（与“观影订单”相同，实现堆叠）
            data: exchangeData,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: '#4198F0' }, // 顶部颜色
                  { offset: 1, color: '#FFFFFF' }, // 底部颜色
                ],
              },
              // borderRadius: [0, 0, 4, 4], // 圆角（底部左右）
            },
            // label: {
            //   show: true,
            //   position: 'inside',
            //   color: '#fff',
            //   formatter: '{c}',
            // },
          },
        ],
      };

      this.myChart.setOption(option);

      // 响应式调整
      window.addEventListener('resize', () => this.myChart.resize());
    },
  },
};
</script>
